/**
	用户
 */
package zstack

import (
	. "bc/util"
	"crypto/sha512"
	"encoding/json"
	"fmt"
	"github.com/pkg/errors"
)

type account struct {

}
func Oauth() (string,error) {
	var au *account
	l := make(map[string]string)
	l["username"] = Config.Zstack.UserName
	l["password"] = Config.Zstack.Password
	result ,err := au.LogInByAccount(l)
	if err != nil{
		return "",err
	}

	if v,ok := result["error"];ok{
		err := errors.New(v.(map[string]interface{})["elaboration"].(string))
		return "",err
	}

	uuid := result["inventory"].(map[string]interface{})["uuid"]
	return uuid.(string),nil
}
/**
	使用账户身份登录
 */
func (a *account) LogInByAccount(l map[string]string) (map[string]interface{},error){

	s512 := sha512.New()
	s512.Write([]byte(l["password"]))

	mmp := map[string]interface{}{
		"logInByAccount":map[string]interface{}{
			"accountName":l["username"],
			"password":fmt.Sprintf("%x",s512.Sum(nil)),
		},
		"systemTags":[]interface{}{},
		"userTags":[]interface{}{},
	}

	data,err := json.Marshal(mmp)
	if err != nil{
		return nil,err
	}

	put ,err := Curl.
		Url(  Config.Zstack.ApiUrl + "v1/accounts/login").
		Header(map[string]string{"Content-Type":"application/json;charset=UTF-8"}).
		Body(string(data)).
		PUT()
	if err != nil{
		return nil,err
	}
	var n = make(map[string]interface{})
	err =json.Unmarshal([]byte(put),&n)
	if err != nil{
		return nil,err
	}
	return n,nil
}
var Account = &account{}